"use strict";
window.onload = function() {
  var vm = new Vue({
    el: "#house",
    data: {
      selectBar:{
        area:'区域',
        subway:'地铁',
        sort:'排序'
      },
      areaList: [],//区域一级列表
      businessList: [],//区域二级列表
      linesList: [],//地铁线列表
      linesbusList: [],//地铁站列表
      hotsearchList: [], //热搜标签
      resourceList: [],
      countVisitsLisst: [],
      houseCollectionNum:[],

      distance: false,
      
      query: {
        distance: "",
        townId: "",
        tradingAreaId: "",
        subwayLineId: "",
        subwayStationId: "",
        sort: "",
        gardenFlag: "",
        gardenType: "",
        priceMax: "9999",
        priceMin: "",
        areaMax: "9999",
        areaMin: "",
        fitmentStatus: "",
        orientation: "",
        floorNoMax: "9999",
        floorNoMin: "",
        managementType: "",
        pubulishCompany: "",
        labelId: "",
        keywords: "",
        page: "1",
        size: "10"
      },
      collectList:[],//id集合
      resourceList:[],//搜索列表集合
      more:true,
      page:1,
      totalNum:0,  
      sortList:[
        {id: "1",name: "高单价优先"},
        {id: "2",name: "低单价优先"},
        // {id: "3",name: "高层建筑优先"},
        // {id: "4",name: "低层建筑优先"},
        // {id: "5",name: "新建建筑优先"},
        // {id: "6",name: "非新建建筑优先"},
        {id: "7",name: "面积大优先"},
        {id: "8",name: "面积小优先"},
        {id: "9",name: "最新优先"}
      ],
      tradingareas: [
        { item_id: "500", item_name: "500米",distance_name:'500米'},
        { item_id: "1000", item_name: "1000米",distance_name:'1000米' },
        { item_id: "2000", item_name: "2000米",distance_name:'2000米' },
        { item_id: "5000", item_name: "5000米",distance_name:'5000米' }
      ],
      priceList: [
        {
          id: "1",
          name: "0～4元/m²·天",
          min: "0",
          max: "4"
        },
        {
          id: "2",
          name: "5～6元/m²·天",
          min: "5",
          max: "6"
        },
        {
          id: "3",
          name: "7～10元/m²·天",
          min: "7",
          max: "10"
        },
        {
          id: "4",
          name: "11～14元/m²·天",
          min: "11",
          max: "14"
        },
        {
          id: "5",
          name: "15元/m²·天以上",
          min: "15",
          max: ""
        }
      ],
      areaLists: [
        {
          id: "1",
          name: "0～100m²",
          min: "0",
          max: "100"
        },
        {
          id: "2",
          name: "100～300m²",
          min: "100",
          max: "300"
        },
        {
          id: "3",
          name: "300～500m²",
          min: "300",
          max: "500"
        },
        {
          id: "4",
          name: "500～1000m²",
          min: "500",
          max: "1000"
        },
        {
          id: "5",
          name: "1000m²以上",
          min: "1000",
          max: ""
        }
      ],
      decorateLists: [
        {
          id: "1",
          name: "毛坯"
        },
        {
          id: "2",
          name: "标配简装"
        },
        {
          id: " 3",
          name: "遗留装修"
        },
        {
          id: "4",
          name: "拎包入住(装修家具)"
        }
      ],
      floor: [
        {
          id: "1",
          name: "低层(1~7)",
          max: "7",
          min: "1"
        },
        {
          id: "2",
          name: "中层(8~15)",
          max: "15",
          min: "8"
        },
        {
          id: "3",
          name: "高层(16~30)",
          max: "30",
          min: "16"
        },
        {
          id: "4",
          name: "超高层(30以上)",
          max: "-1",
          min: "30"
        }
      ],
      toward: [
        {
          id: "0",
          name: "东"
        },
        {
          id: "1",
          name: "南"
        },
        {
          id: "2",
          name: "西"
        },
        {
          id: "3",
          name: "北"
        }
      ],
      theissuer: [
        {
          id: "0",
          name: "个人业主"
        },
        {
          id: "1",
          name: "开发商"
        },
        {
          id: "2",
          name: "资产管理公司"
        },
        {
          id: "3",
          name: "中介公司"
        }
      ],
      propertyList: [
        {
          id: "1",
          name: "国企"
        },
        {
          id: "2",
          name: "私企"
        },
        {
          id: "5",
          name: "合资"
        },
        {
          id: "3",
          name: "港澳台资"
        },
        {
          id: "4",
          name: "外资"
        }
      ],
      gardenType: [
        {
          id: "1",
          name: "文创"
        },
        {
          id: "2",
          name: "科技"
        },
        {
          id: "3",
          name: "其他"
        }
      ],
      type: [
        {
          id: "1",
          name: "园区"
        },
        {
          id: "0",
          name: "写字楼"
        }
      ],
      byCompany:false,
      companyList:[],
      companyIdList:[],
      companyMore:false,
      companyTotalNum:0,
      countVisitsLisst2:[]

    },
    created: function() {
      if (this.getCookie("signature")) {
        this.token = this.getCookie("signature");
      }
      if (this.IEVersion() !== -1) {
        var kword = decodeURI(this.getParams("keyword"));
      } else {
        var kword = decodeURI(escape(this.getParams("keyword")));
      }
      this.query.keywords = kword;
      this.byCompany = Number(this.getParams("isCompany"))?true:false;
      this.getCommonCityItems();
      this.getHotSearch();
      var pubulishCompany = this.getParams("pubulishCompany");  
      this.query.pubulishCompany = this.getParams("pubulishCompany");    
      var townId = this.getParams("town");
      this.query.townId = this.getParams("town");      
      this.query.gardenFlag = this.getParams("id");
      this.search();
      
      // this.switchByCompany();
    },
    methods: {
      // 获取参数
      getParams: function(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return "";
      },    
      // 根据城市id获取区县
      getCommonCityItems: function() {
        var $this = this;
        house_server.getCommonCityItems({cityId: "1"}, function(res) {
            if (res.code == 200) {
              var params = res.data.params[0];
              //为区域和地铁线下一级列表加全部选项             
              let areaList = params.towns; // 区域 
              areaList.unshift({item_id:'',item_name:'全部',tradingareas:[]});//区域加全部             
              areaList.forEach(item=>{
                item.tradingareas.unshift({item_id:item.item_id,item_name:'全部',parent_name:item.item_name})
              })
              $this.areaList = areaList;  
              $this.getHotTradingArea();
              $this.getArea('',areaList[0]);  
              $this.query.townId && $this.getArea('init');//首次加载且url里带有townId
              let linesList = params.lines; //地铁线
              let lineAllObj = {item_id:'',item_name:'全部',stations:[]};//地铁线加全部
              linesList.unshift(lineAllObj);
              linesList.forEach(item=>{
                item.stations.unshift({item_id:item.item_id,item_name:'全部',parent_name:item.item_name})
              })
              $this.linesList = linesList;
              $this.getlines(linesList[0]);
            }
          });
      }, 
      // 区域
      getHotTradingArea: function() {
        var _this = this;
        house_server.getHotTradingArea({}, function(res) {
          res.data.forEach(function(element) {
            element.item_name = element.tradingArea;
            element.item_id = element.tradingAreaId;
          });
          _this.areaList.splice(1,0,
              {item_id: "distance",item_name: "附近",tradingareas: _this.tradingareas},
              {item_id: "hot",item_name: "热门商圈",tradingareas: res.data});
        });
      },
      //获取商圈
      getArea: function(str,area) {
        if(str == 'init'){//首次加载且url里带有townId
            this.areaList.forEach((item,index)=>{
                if(this.query.townId == item.item_id){
                    this.businessList = item.tradingareas; 
                    this.selectBar.area = item.item_name;
                }
            })
        }else{
            this.query.townId = area.item_id;
            this.businessList = area.tradingareas; 
        }  
      },
      // 点击商圈
      getbus(business){
        if('tradingAreaId' in business){//点击热门商圈
            this.query.distance="";
            this.query.townId='hot';
            this.query.tradingAreaId = business.item_id;
            this.selectBar.area = this.query.tradingAreaId==''?'区域':business.item_name;
        }else if('distance_name' in business){//点击附近
            this.query.townId='distance';
            this.query.tradingAreaId = "";
            this.query.distance = business.item_id;
            this.selectBar.area = this.query.distance==''?'区域':business.item_name;
        }else{//点击正常区域
            this.query.distance="";
            this.query.tradingAreaId='';
            if(business.item_name == '全部'){
                this.query.townId = business.item_id;
                this.selectBar.area = this.query.townId==''?'区域':business.parent_name; //把选中的值放到筛选头上
            }else{
                this.query.tradingAreaId = business.item_id;
                this.selectBar.area = this.query.tradingAreaId==''?'区域':business.item_name;
            }
        }
        this.search();
        $(".third-info").hide();
        $(".all-list").show(100);
      },
      //地铁线
      getlines: function(lines) {
        this.query.subwayLineId = lines.item_id;
        this.linesbusList = lines.stations;
      },
      getlibus: function(libus) {
        this.query.subwayStationId ='';
        if(libus.item_name == '全部'){
          this.query.subwayLineId = libus.item_id;
          this.selectBar.subway = this.query.subwayLineId==''?'地铁':libus.parent_name; //把选中的值放到筛选头上
        }else{
          this.query.subwayStationId = libus.item_id;
          this.selectBar.subway = this.query.subwayStationId==''?'地铁':libus.item_name;
        }
        this.search();
        $(".third-info").hide();
        $(".all-list").show(100);
      },
      //排序
      sort(item){
        this.query.sort = this.query.sort==item.id?'':item.id;//0-升 1-降
        this.selectBar.sort = this.query.sort==''?'排序':item.name;
        this.search();
      },
      //获取热搜便签
      getHotSearch: function() {
        var $this = this;
        house_server.getHotSearch({type: "3"},function(res) {
            if (res.code == 200) {
              $this.hotsearchList = res.data;
            }
          });
      },
      handleChooseSelect(type,param){
        switch(type){
            case 'type':
                this.query.gardenFlag = this.query.gardenFlag==param.id?'':param.id;
                this.query.gardenType = "";//切换时联动选项
                break;
            case 'gardenType':
                this.query.gardenType = this.query.gardenType==param.id?'':param.id;
                break;
            case 'price':  
                if(this.query.priceMin == param.min){
                  this.query.priceMax  = "9999";  
                  this.query.priceMin  = "";  
                }else{
                  this.query.priceMax  = param.max;  
                  this.query.priceMin  = param.min;
                }
                break;  
            case 'area':  
                if(this.query.areaMin == param.min){
                  this.query.areaMax  = "9999";  
                  this.query.areaMin  = "";  
                }else{
                  this.query.areaMax  = param.max;  
                  this.query.areaMin  = param.min;
                }
                break;       
            case 'fitmentStatus':
                this.query.fitmentStatus =  this.query.fitmentStatus==param.id?'':param.id;
                break; 
            case 'floor':  
                if(this.query.floorNoMin == param.min){
                  this.query.floorNoMax  = "9999";  
                  this.query.floorNoMin  = "";  
                }else{
                  this.query.floorNoMax  = param.max;  
                  this.query.floorNoMin  = param.min;
                }
                break;  
            case 'toward':
                this.query.orientation = this.query.orientation==param.id?'':param.id;
                break; 
            case 'managementType':
                this.query.managementType = this.query.managementType==param.id?'':param.id;  
                break; 
            case 'pubulishCompany':
                this.query.pubulishCompany = this.query.pubulishCompany==param.id?'':param.id;  
                break; 
            case 'hotsearch':
                 this.query.labelId = this.query.labelId==param.tagId?'':param.tagId;    
                 break;       
        }
      },
      reset(){
        this.query.gardenFlag = "";
        this.query.gardenType ="";
        this.query.priceMax  = "9999";  
        this.query.priceMin  = "";
        this.query.areaMax  = "9999";  
        this.query.areaMin  = "";
        this.query.fitmentStatus = "";
        this.query.floorNoMax  = "9999";  
        this.query.floorNoMin  = "";  
        this.query.orientation = "";
        this.query.managementType = ""; 
        this.query.pubulishCompany = "";  
        this.query.labelId = ""; 
      },
      //搜索
      search(){
        this.query.page = 1;
        if(this.byCompany){
          this.searchByCompany(0);
        }else{
          this.searchBuildingHousePage(0);
        }
      },
      //房源搜索
      searchBuildingHousePage: function(more) {
        var $this = this;
        this.houseCollectionNum = [];
        this.resourceList = more ? this.resourceList : [];
        this.collectList = more ? this.collectList : [];
        //为了把<热门商圈>和<附近>的active状态留住，在这用临时变量接一下，过滤掉非法的townId值
        let query1 = JSON.parse(JSON.stringify(this.query));
        if((query1.townId == 'distance')||(query1.townId == 'hot')){
          query1.townId="";
        }
        house_server.getSearchBuildingHousePage(query1, function(res) {
          if (res.code == 200) {
            if(res.data.rows.length>0){
                res.data.rows.forEach(function(element) {
                    switch (element.fitmentStatus) {
                      case "1":
                        element.fitmentTxt = "毛坯";
                        break;
                      case "2":
                        element.fitmentTxt = "标配简装";
                        break;
                      case "3":
                        element.fitmentTxt = "遗留装修";
                        break;
                      case "4":
                        element.fitmentTxt = "拎包入住";
                        break;
                    }
                    $this.resourceList.push(element);
                    $this.collectList.push(element.id);
                  });
                  setTimeout(function() {
                    $this.getCountVisits($this.collectList, 1);
                    $this.getHouseCollectionNums($this.collectList);
                  }, 500);
            }
            if($this.query.page ==1){
                $this.more = res.data.total>$this.query.size;
                $this.totalNum = res.data.total;
            }
            
          }
        });
        $(".third-info").hide();
        $(".all-list").show(100);
      }, 
      loadMore(){
        this.query.page++;
        this.searchBuildingHousePage(1);
        if(this.query.page>=(this.totalNum / this.query.size)){
          this.more = false ;
        }
      },  
      goDetail(item){
        window.open( "/three/household.html?name="+item.building3dNo+"&cnt=0&houseid="+item.id+"&buildid="+item.buildingId);
      },
      goDetail1(item){
        window.open( "/three/household.html?name="+item.building3dCode+"&cnt=0&houseid="+item.houseId+"&buildid="+item.buildingId);
      },
      //统计浏览量多个
      getCountVisits: function(list, types) {
        var $this = this;
        house_server.getCountVisits({ids: list,type:types==1? "3":"8"},function(data) {
            if (types == 1) {
              $this.countVisitsLisst = data.data;
            } else {
              $this.countVisitsLisst2 = data.data;
            }
          }
        );
      },
      // 收藏(多)
      getHouseCollectionNums: function(idList) {
        var $this = this;
        house_server.getHouseCollectionNums({houseIds: idList},function(res) {
            $this.houseCollectionNum = res.data;
          }
        );
      },
      //按公司显示
      searchByCompany(more){
        var $this = this;
        this.companyList = more ? this.companyList : [];
        this.companyIdList = more ? this.companyIdList : [];
        let idList=[];//房源浏览量
        house_server.searchByHousePage(this.query, function(res) {
          if (res.code == 200) {
            res.data.companyList.forEach(function(item) {
              idList=[] ;
              item.houseList.forEach(function(data) {
                idList.push(data.houseId);
              });
              item['houseCountVisits'] = $this.getHouseCountVisits(idList);
              $this.companyList.push(item);
              $this.companyIdList.push(item.companyId);
              
            });
            setTimeout(function() {
              $this.getCountVisits($this.companyIdList);
            }, 500);
            if($this.query.page ==1){
                $this.companyMore = res.data.total>$this.query.size;
                $this.companyTotalNum = res.data.total;
            }
            $(".third-info").hide();
            $(".all-list").show(100);
          }
        });
        // console.log($this.companyList);
      },
      getHouseCountVisits: function(ids) {
        let query1 = {ids: ids,type: "3"},
        $this = this;
        let idArr = [];
        house_server.getCountVisits(query1, function(res) {
          res.data.forEach(function(item) {
            idArr.push(item);
          });
        });
        return idArr;
      },
      loadMoreCompany(){
        this.query.page++;
        this.searchByCompany(1);
        if(this.query.page>=(this.companyTotalNum / this.query.size)){
          this.companyMore = false ;
        }
      },
      goCompany(company){
        // console.log(company)
        window.location.href="../others/company.html?id="+company.companyId;
      },
      switchByCompany(){
        this.byCompany = !this.byCompany;
        this.query.page = 1;//切换接口，page置为第一页
        this.search();
      },
      // 转化时间
      forDate: function(time) {
        var timestamp = (new Date(time.replace(/-/g, "/")) * 1) / 1000;
        function zeroize(num) {
          return (String(num).length == 1 ? "0" : "") + num;
        }
        var curTimestamp = parseInt(new Date().getTime() / 1000); //当前时间戳
        var timestampDiff = curTimestamp - timestamp; // 参数时间戳与当前时间戳相差秒数
        var curDate = new Date(curTimestamp * 1000); // 当前时间日期对象
        var tmDate = new Date(timestamp * 1000); // 参数时间戳转换成的日期对象

        var Y = tmDate.getFullYear(),
          m = tmDate.getMonth() + 1,
          d = tmDate.getDate();
        var H = tmDate.getHours(),
          i = tmDate.getMinutes(),
          s = tmDate.getSeconds();
        if (timestampDiff < 60) {
          // 一分钟以内
          return "刚刚";
        } else if (timestampDiff < 3600) {
          // 一小时前之内
          return Math.floor(timestampDiff / 60) + "分钟前";
        } else if (
          curDate.getFullYear() == Y &&
          curDate.getMonth() + 1 == m &&
          curDate.getDate() == d
        ) {
          return "今天" + zeroize(H) + ":" + zeroize(i);
        } else {
          var newDate = new Date((curTimestamp - 86400) * 1000); // 参数中的时间戳加一天转换成的日期对象
          if (
            newDate.getFullYear() == Y &&
            newDate.getMonth() + 1 == m &&
            newDate.getDate() == d
          ) {
            return "昨天" + zeroize(H) + ":" + zeroize(i);
          } else if (curDate.getFullYear() == Y) {
            return (
              zeroize(m) +
              "月" +
              zeroize(d) +
              "日 " +
              zeroize(H) +
              ":" +
              zeroize(i)
            );
          } else if (timestampDiff < 259200000) {
            return Math.floor(timestampDiff / 86400000) + "天前";
          } else {
            return (
              Y +
              "年" +
              zeroize(m) +
              "月" +
              zeroize(d) +
              "日 " +
              zeroize(H) +
              ":" +
              zeroize(i)
            );
          }
        }
      },
      // 判断浏览器类别
      IEVersion: function() {
        var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
        var isIE =
          userAgent.indexOf("compatible") > -1 &&
          userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器
        var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器
        var isIE11 =
          userAgent.indexOf("Trident") > -1 &&
          userAgent.indexOf("rv:11.0") > -1;
        if (isIE) {
          var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
          reIE.test(userAgent);
          var fIEVersion = parseFloat(RegExp["$1"]);
          if (fIEVersion == 7) {
            return 7;
          } else if (fIEVersion == 8) {
            return 8;
          } else if (fIEVersion == 9) {
            return 9;
          } else if (fIEVersion == 10) {
            return 10;
          } else {
            return 6; //IE版本<=7
          }
        } else if (isEdge) {
          return "edge"; //edge
        } else if (isIE11) {
          return 11; //IE11
        } else {
          return -1; //不是ie浏览器
        }
      },
      // 获取cookie
      getCookie: function(cname) {
        var name = cname + "=";
        var ca = document.cookie.split(";");
        for (var i = 0; i < ca.length; i++) {
          var c = ca[i].trim();
          if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
        }
        return "";
      },
      //获取图片路径
      getImgUrl: function() {
        var ip = window.location.host,
          url = "";
        if (ip.indexOf("127.0.0.1") >= 0 || ip.indexOf("localhost") >= 0) {
          url = "http://114.113.68.14:9000/image/";
        } else if (ip.indexOf("www.") >= 0) {
          url = "http://image.3dzhixuan.com/image/";
        } else {
          url = "http://" + ip + "/image/";
        }
        return url;
      },
    }
  });
};
